import { ipcMain, Menu } from 'electron'
import { IpcEvent } from 'app/type'
import { IpcMainInvokeEvent, MenuItemConstructorOptions, PopupOptions } from 'electron/main'

export class ContextMenu {
    static popup(menuOptions: MenuItemConstructorOptions[], popupOptions?: Electron.PopupOptions) {
        const menu = Menu.buildFromTemplate(menuOptions)
        menu.popup(popupOptions)
        return menu
    }

    static init() {
        ipcMain.handle(
            IpcEvent.MENU_STEUP_CONTEXT,
            async (e: IpcMainInvokeEvent, options: PopupOptions) => {
                const menu: MenuItemConstructorOptions[] = [
                    { label: '刷新', click: () => e.sender.reload() },
                    {
                        label: '返回',
                        click: () => e.sender.goBack(),
                        visible: e.sender.canGoBack(),
                    },
                    {
                        label: '前进',
                        click: () => e.sender.goForward(),
                        visible: e.sender.canGoForward(),
                    },
                    { label: '切换控制台', click: () => e.sender.toggleDevTools() },
                ]
                ContextMenu.popup(menu, options)
            },
        )
    }
}
